package com.china08.yxyapi.service.manage.edu.platform.statistics.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.api.manage.edu.platform.statistics.resourcepandect.ResourceModel;
import com.china08.yxyapi.repository.db.yxy.YxyAreaRepository;
import com.china08.yxyapi.service.manage.edu.platform.statistics.ResourceCountListService;

/**
 * 资源统计 资源统计列表
 * 
 * @author yyy
 *
 */
@Service
public class ResourceCountListServiceImpl implements ResourceCountListService {
    @Autowired
    private ElasticsearchTemplate et;
    @Autowired
    private YxyAreaRepository yxyAreaRepository;

    @Override
    public Page<ResourceModel> getAreaResourceCount(String districtCode, Integer schoolBureauLevel, String sort,
            Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        if (schoolBureauLevel == 0) {
            TermQueryBuilder builderDel = new TermQueryBuilder("districtCode", districtCode);
            boolQueryBuilder.must(builderDel);

            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(2000);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                key = yxyAreaRepository.findByAreaId(key).getAreaName();

                long value = gradeBucket.getDocCount();
                map.put(key, value);

                System.out.println("区县" + key + "科目有" + value + "个资源。");
                System.out.println();
            }
        } else if (schoolBureauLevel == 1) {
        	
        	
        	
            TermQueryBuilder builderDel = new TermQueryBuilder("cityCode", districtCode);
            boolQueryBuilder.must(builderDel);

            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(2000);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                key = yxyAreaRepository.findByAreaId(key).getAreaName();
                long value = gradeBucket.getDocCount();
                map.put(key, value);

                System.out.println("市" + key + "区县有" + value + "个资源。");
                System.out.println();
            }
        } else if (schoolBureauLevel == 2) {
            TermQueryBuilder builderDel = new TermQueryBuilder("provinceCode", districtCode);
            boolQueryBuilder.must(builderDel);

            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("cityCode").size(2000);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                key = yxyAreaRepository.findByAreaId(key).getAreaName();
                long value = gradeBucket.getDocCount();
                map.put(key, value);

                System.out.println("省" + key + "市有" + value + "个资源。");

                System.out.println();
            }
        }

        List<ResourceModel> resourceModelLst = new ArrayList<ResourceModel>();
        ResourceModel resourceModel = null;
        Integer order = 0;
        for (String key : map.keySet()) {
            resourceModel = new ResourceModel();
            order += 1;
            resourceModel.order = order;
            resourceModel.areaName = key;
            resourceModel.areaCount = Long.parseLong(map.get(key).toString());
            resourceModelLst.add(resourceModel);
        }
         //如果是倒序
		if (sort.equals("DESC")) {
			Collections.sort(resourceModelLst, new Comparator<ResourceModel>(){
				@Override
				public int compare(ResourceModel o1, ResourceModel o2) {
					// TODO Auto-generated method stub
					long i=o2.getAreaCount() - o1.getAreaCount();
					return (int) i;
				}
			});
		} else if (sort.equals("ASC")) {
			Collections.sort(resourceModelLst, new Comparator<ResourceModel>(){
				@Override
				public int compare(ResourceModel o1, ResourceModel o2) {
					// TODO Auto-generated method stub
					long i=o1.getAreaCount()-o2.getAreaCount();
					return (int) i;
				}
			});
		}
		
        List<ResourceModel> resourceModelLst1 = new ArrayList<ResourceModel>();
        PageImpl<ResourceModel> pageImpl = null;
        if (resourceModelLst.size() > 10) {
//            System.out.println("------" + pageable.getPageNumber());
        	 Integer pageNum=0;
        	 if ((pageable.getPageNumber()+1)*10 > resourceModelLst.size()) {
        		 pageNum = resourceModelLst.size();
			 }else{
				 pageNum = (pageable.getPageNumber()+1)*10;
			 }
        	
            resourceModelLst1 = resourceModelLst.subList((pageable.getPageNumber()) * pageable.getPageSize(), pageNum);
            pageImpl = new PageImpl<ResourceModel>(resourceModelLst1, pageable, resourceModelLst.size());
        } else {
            resourceModelLst1 = resourceModelLst;
            pageImpl = new PageImpl<ResourceModel>(resourceModelLst1, pageable, resourceModelLst.size());
        }
        Page<ResourceModel> page = pageImpl;

        return page;
    }

    @Override
    public Page<ResourceModel> getResourceCountLst(String districtCode, Integer schoolBureauLevel, Pageable pageable) {

        return null;
    }
}